<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-button
						type="warning"
						:loading="exportLoading"
						icon="el-icon-upload2"
						size="small"
						class="item-gap"
						@click="onExportExcel"
					>导出</jk-button>
				</div>
				<div class="flex-end-center-wrap">
					<el-checkbox v-model="searchParams.ifOnShift" label="当班" border class="item-gap" size="small" @change="checkboxChange"></el-checkbox>
					<jk-date-picker v-model="searchParams.belongDate" type="daterange" placeholder="日期" :picker-options="pickerOptions" :disabled="searchParams.ifOnShift" size="small" style="width: 280px;" class="margin-5-0 item-gap" clearable />
					<!--					<jk-select v-model="searchParams.workshopId" :option-list="workshopList" clearable placeholder="区域" size="small" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>-->
					<el-select v-model="searchParams.processCode" clearable placeholder="工序" size="small" class="search-bar-item-size2 margin-5-0 item-gap">
						<el-option v-for="item in processList" :key="item.id" :label="item.name" :value="item.code" />
					</el-select>
					<jk-search-input v-model="searchParams.productNameOrCode" placeholder="品种名称" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-button class="" @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>
		<jk-card>
			<jk-table
				ref="frontGroupSalaryMonthReportTable"
				border
				show-footer
				:span-method="mergeColMethod"
				:footer-method="footerMethod"
				:data="tableData"
				:height="tableHeight + 20"
				:loading="tableLoading"
			>
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
				</vxe-column>
			</jk-table>
			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="searchParams.count"
					@on-change="onPage"
				/>
			</footer>
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { formatDate, pageConfig, formatTime } from '/src/utils/jk/jk-tool';
    import permissionMixin from '../../../mixins/permission-mixin';
    import {
        reportProductionYieldGetData
    } from '../../../api/statistic/varietyYieldStatement';
    import { systemUserColumnConfigGet } from '@/api/system/column-config';
    import tubeColor from '@/views/basicData/tubeColor/index.vue';
    import shiftSelect from '@/views/jk-components/jk-shift-select/index.vue';
    import XEUtils from 'xe-utils';
    export default {
        name: 'VarietyYieldStatement',
        computed: {
            tubeColor() {
                return tubeColor;
            }
        },
        mixins: [permissionMixin, calHeight],
        components: {
            shiftSelect
        },
        data: function() {
            return {
                prefix: '',
                processList: [],
                workshopList: [],
                tableColumnList: [],
                shiftList: [],
                dataId: null,
                tableLoading: false,
                exportLoading: false,
                tableData: [],
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    }
                },
                noCalKey: ['allQty'],
                searchParams: {
                    count: 0,
                    machineCode: null,
                    productNameOrCode: undefined,
                    belongDate: [],
                    ifOnShift: true,
                    selectTimeState: 0,
                    productNames: ''
                    // workshopId: null
                },
                scheduleShiftList: {}
            };
        },
        methods: {
            getMenuColumnListRequest() {
                return systemUserColumnConfigGet({ path: 'VarietyYieldStatement', filterShow: true }).then(res => {
                    if (res.data.status === 200) {
                        this.tableColumnList = res.data.res.columnConfigList && res.data.res.columnConfigList.length ? res.data.res.columnConfigList[0].itemList : [];
                    }
                });
            },

            mergeColMethod({ row, _rowIndex, column, visibleData }) {
                const prevRow = visibleData[_rowIndex - 1];
                let nextRow = visibleData[_rowIndex + 1];
                if (column.property === 'belongDate') {
                    if (prevRow && prevRow.belongDate === row.belongDate) {
                        return { rowspan: 0, colspan: 0 };
                    } else {
                        let countRowspan = 1;
                        while (nextRow && nextRow.belongDate === row.belongDate) {
                            nextRow = visibleData[++countRowspan + _rowIndex];
                        }
                        if (countRowspan > 1) {
                            return { rowspan: countRowspan, colspan: 1 };
                        }
                    }
                }
            },
            footerMethod({ columns, data }) {
                return [
                    columns.map((column, columnIndex) => {
                        if (columnIndex === 0) {
                            // return `合计: ${this.totalData.totalOutputM || 0}M; ${this.totalData.totalOutputKg || 0}KG`;
                            return `合计`;
                        }
                        if (this.noCalKey.includes(column.property)) {
                            return XEUtils.sum(data, column.property);
                        }
                        return null;
                    })
                ];
            },
            checkboxChange() {
                if (this.searchParams.ifOnShift === true) {
                    this.searchParams.selectTimeState = 0;
                } else {
                    this.searchParams.selectTimeState = '';
                }
                this.$set(this.searchParams, 'belongDate', []);
            },
            onPage(e, size) {
                this.searchParams.pageNo = e;
                this.searchParams.pageSize = size;
                this.getListRequest();
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                if (params.belongDate) {
                    params.startDate = params.belongDate[0];
                    params.endDate = params.belongDate[1];
                }
                delete params.belongDate;
                delete params.productNames;
                reportProductionYieldGetData(params).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.searchParams.count = res.data.count;
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.searchParams.count = 1;
                this.getListRequest();
            },
            /** 导出按钮操作 */
            onExportExcel() {
                this.exportLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                if (params.belongDate) {
                    params.startDate = params.belongDate[0];
                    params.endDate = params.belongDate[1];
                }
                delete params.belongDate;
                delete params.productNames;
                this.$modal.confirm('是否确认导出所有数据数据项?').then(() => {
                    this.exportLoading = true;
                    return reportProductionYieldGetData(params);
                }).then(res => {
                    if (res.data.status === 200) {
                import('@/vendor/Export2Excel').then(excel => {
                  const titleList = this.tableColumnList.map(x => x.title);
                  const keyList = this.tableColumnList.map(x => x.keyName);
                  const list = res.data.res ? res.data.res : [];
                    // 合计项
                    const totalItem = {};
                    keyList.forEach((x, idx) => {
                        totalItem[x] = this.$refs.frontGroupSalaryMonthReportTable.$refs.xTable.getTableData().footerData[0][idx];
                    });
                    list.push(totalItem);
                    const data = list.map(v => keyList.map(j => v[j]));
                  excel.export_json_to_excel({
                    header: titleList,
                    data,
                    filename: `${this.$route.meta.title}(${formatDate(Date.now())})`,
                    autoWidth: true,
                    bookType: 'xlsx'
                  });
                });
                    }
                    this.exportLoading = false;
                });
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                    return v[j];
                }));
            },
            getOneFloat(num) {
                const numMain = Number(num);
                return parseFloat(numMain.toFixed(1));
            },
            minification(num) {
                const numMain = Number(num);
                return numMain / 100;
            },
            async getDependentData() {
                // this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                this.processList = this.$store.state.user.userProcess.processList;
                if (!this.searchParams.processCode) {
                    this.$set(this.searchParams, 'processCode', this.$store.state.user.userProcess.defaultProcessCode || 'XS');
                }
                // if (!this.searchParams.workshopId) {
                //     this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                // }
                await this.getListRequest();
            }
        },
        mounted() {
            this.getMenuColumnListRequest();
            this.getDependentData();
        }
    };
</script>
<style scoped>
</style>
